﻿using System;
using System.Collections.Generic;
using System.Text;
using Layui.Entities;
using Microsoft.Extensions.Caching.Memory;
using System.Linq;

namespace Layui.Services.Setting
{
    public class SettingService : ISettingService
    {
        private const string MODEL_KEY = "Layui.services.setting";

        private IMemoryCache _memoryCache;
        private LayuiDbContext _LayuiDbContext;

        public SettingService(IMemoryCache memoryCache,
            LayuiDbContext LayuiDbContext)
        {
            this._LayuiDbContext = LayuiDbContext;
            this._memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取所有并缓存
        /// </summary>
        /// <returns></returns>
        public List<Entities.Setting> GetAllCache()
        {
            List<Entities.Setting> result = null;
            if (!_memoryCache.TryGetValue<List<Entities.Setting>>(MODEL_KEY, out result))
            {
                result = _LayuiDbContext.Settings.ToList();
                _memoryCache.Set(MODEL_KEY,result, DateTimeOffset.Now.AddDays(1));
            }
            return result;
        }

        /// <summary>
        /// 保存基数设置的值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public (bool Status, string Message) SaveSetting(string name, string value)
        {
            var item = _LayuiDbContext.Settings.FirstOrDefault(o => o.Name == name);
            if (item == null)
            {
                _LayuiDbContext.Settings.Add(new Entities.Setting()
                {
                    Id = Guid.NewGuid(),
                    Name = name,
                    Value = value
                });
            }
            else
            {
                item.Value = value;
            }
            _LayuiDbContext.SaveChanges();
            _memoryCache.Remove(MODEL_KEY);
            return (true, "保存成功");
        }
    }
}
